<template>
  <el-dialog
    top="10vh"
    width="500px"
    :title="form.id ? '编辑分类' : '新增分类'"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      size="small"
    >
      <el-form-item label="上级分类">
        <el-cascader
          v-model="form.parent_id"
          :options="categoryOptions"
          :props="{ checkStrictly: true, value: 'id', label: 'name' }"
          clearable
          placeholder="请选择上级分类"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" :max="999" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit" :loading="loading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'CategoryForm',
  data() {
    return {
      dialogVisible: false,
      loading: false,
      categoryOptions: [],
      form: {
        id: '',
        parent_id: 0,
        name: '',
        sort: 0,
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 打开弹窗
    open(row) {
      console.log(row)
      this.dialogVisible = true
      this.getCategoryOptions()
      if (row) {
        this.form = { ...row }
      } else {
        this.form = {
          id: '',
          parent_id: 0,
          name: '',
          sort: 0,
          status: 1
        }
      }
    },
    // 获取分类选项
    getCategoryOptions() {
      http.category.list().then(res => {
        this.categoryOptions = res.data
      })
    },
    // 提交表单
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const api = this.form.id ? http.category.update : http.category.create
          const params = { ...this.form }

          api(undefined,params).then(() => {
            this.$message.success(this.form.id ? '更新成功' : '创建成功')
            this.dialogVisible = false
            this.$emit('refresh')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
